package com.show.web.event;

import com.alibaba.fastjson.JSON;
import com.show.util.FileUtil;
import com.show.util.HelperClazz;
import com.show.dao.event.EventRepositoty;
import com.show.dto.Event;
import com.show.dto.activiti.TaskBean;
import com.show.dto.draw_time.DrawTime;
import com.show.dto.grid.Grid;
import com.show.dto.message_acessory.MessageAccessory;
import com.show.dto.public_security.PublicSecurity;
import com.show.dto.sys_emp.SysEmp;
import com.show.dto.sys_org.SysOrg;
import com.show.dto.sys_role.SysRole;
import com.show.filter.LoginController;
import com.show.service.draw_time.DrawTimeService;
import com.show.service.eact.EactServer;
import com.show.service.eact.EasyActService;
import com.show.service.emp.EmpOrgService;
import com.show.service.emp.EmpService;
import com.show.service.event.EventService;
import com.show.service.grid.GridService;
import com.show.service.kv.KVService;
import com.show.service.org.SysOrgService;
import com.show.service.role.RoleService;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 工作流
 *
 * @Auther : 王硕
 * @Param :
 * @date : 2018-01-29 上午 9:56
 */
@RestController
@RequestMapping(value = "/event")
public class EventController {

    @Autowired
    private EventService eventService;
    @Autowired
    private EactServer eactServer;
    @Autowired
    private EasyActService easyActService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private EventRepositoty eventRepositoty;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private EmpService empService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private EmpOrgService empOrgService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private GridService gridService;
    @Autowired
    private DrawTimeService drawTimeService;
    @Autowired
    private KVService kvService;
    @Autowired
    private FileUtil fileUtil;

    /**
     * 新增事件
     *
     * @param
     * @return
     */
    @PostMapping("/insertEvent")
    public String insertEvent(Event event) throws Exception {//MultipartFile[] file
        Integer eventId;
        Integer result = -1;
        if("网格类".equals(event.getEventType())){
            eventId = eventService.insertEvent(event,"pc");
            if (eventId != 0 && eventId != -1) {
                event.setEventId(eventId);
                String messageAccessoryIds = eventService.saveMessageAccessory(event.getImgStr(), event.getAudioStr(), event.getVedioStr(), eventId.toString());
                result = this.startProcess(event, event.getOutcome(), messageAccessoryIds);
            } else {
                result = -1;
            }
        }else if("治安类".equals(event.getEventType())){
            eventId = eventService.insertPublicSecurity(event, "pc");
            if (eventId != 0 && eventId != -1) {
                List<PublicSecurity> publicSecurityList = eventService.findOneForPublicSecurity(eventId.toString());
                String messageAccessoryIds = eventService.saveMessageAccessory(event.getImgStr(), event.getAudioStr(), event.getVedioStr(), eventId.toString());
                PublicSecurity publicSecurity = publicSecurityList.get(0);
                publicSecurity.setMessageAccessoryIds(messageAccessoryIds);
                result = eventService.updateForPublicSecurity(publicSecurity);
            } else {
                result = -1;
            }
        }else{
            return "案件类型不符合";
        }

        if (result == 1) {
            return "上报成功";
        } else {
            if("网格类".equals(event.getEventType())){
                //上传失败删除本地库
                eventService.deleteEvent(event);
            }
            return "上报失败";
        }
    }

    /**
     * 附件回显
     *
     * @author 姜文
     * @Param
     * @date 2018年3月7日, PM 04:18:25
     */
    @PostMapping("/getEventAccessory")
    public List<MessageAccessory> getEventAccessory(String eventId) throws Exception {
        //根据eventId  查询附件
        List<MessageAccessory> list = eventService.findByEventId(eventId);
        for (MessageAccessory e : list) {
            e.setAccessoryPath(fileUtil.getShowUrl() + e.getAccessoryName());
        }
        return list;
    }

    /**
     * 上传附件
     *
     * @author 姜文
     * @Param
     * @date 2018年3月7日, PM 04:18:25
     */
    @RequestMapping("/getImgFileName")
    public String getImgFileName(@RequestParam("imgFile") MultipartFile imgFile) {
        String imgName = fileUtil.saveFile(imgFile);
        return JSON.toJSONString(imgName);
    }

    @RequestMapping("/getAudioFileName")
    public String getAudioFileName(@RequestParam("audioFile") MultipartFile audioFile) {
        String audioName = fileUtil.saveFile(audioFile);
        return JSON.toJSONString(audioName);
    }

    @RequestMapping("/getVedioFileName")
    public String getVedioFileName(@RequestParam("vedioFile") MultipartFile vedioFile) {
        String vedioName = fileUtil.saveFile(vedioFile);
        return JSON.toJSONString(vedioName);
    }


    /**
     * 获取可上报的角色
     *
     * @return
     */
    @RequestMapping("/getReportedRole")
    public List<SysRole> getReportedRole() {
        return roleService.getReportedRole();
    }

    /**
     * 将任务添加到工作流
     *
     * @param event
     * @param outcome
     * @return
     */
    @RequestMapping("/startProcess")
    public Integer startProcess(Event event, String outcome, String messageAccessoryIds) throws Exception {
        eactServer.saveStartProcess(Event.class.getSimpleName(), event.getEventId().toString(), event.getEmpId().toString());
        List<TaskBean> list = eactServer.findTaskList(event.getEmpId().toString());
        String taskId = "";
        String assignee = "";
        Integer empId = event.getEmpId();
        String orgId = empOrgService.getOrgByempId(empId).get(0).getOrgId();
        Integer pOrgId = sysOrgService.getParentOrgId(orgId);
        //部门_连线名称_登陆人姓名_附件Ids
        String userMassage = this.getUserMassage(empId, messageAccessoryIds, outcome);
        if (list.size() > 0) {
            taskId = list.get(0).getTaskId();
        }
        if ("上报社区".equals(outcome)) {
            //上报当前登陆人所在社区
            assignee = orgId + ".18";
        } else if ("直报街道".equals(outcome)) {
            //上报当前登陆人所在街道
            assignee = pOrgId + ".17";
        }
        try {
            String result = eactServer.completeTask(taskId, outcome, event.getEventContent(), userMassage, assignee, assignee);//完成任务
            return 1;
        } catch (Exception e) {
            eventRepositoty.delete(event);
            eactServer.deleteProcessInstance(taskId);
            return -1;
        }
    }

    /**
     * 领取任务
     *
     * @return
     */
    @RequestMapping("/claim")
    public String claim(String eventId, HttpServletRequest request) {
        /* 当前登陆人姓名及信息 */
        Map<String, Cookie> cookieMap = HelperClazz.ReadCookieMap(request);
        Cookie cookie = (Cookie) cookieMap.get("userName");
        String userName = cookie.getValue().replace("'", "");
        SysEmp emp = empService.getEmpByLogin(userName);

        /* 根据empId查询roleIds */
        String roleids = "";
        String orgId = sysOrgService.getOrgIdByEmpId(emp.getEmpId().toString());
        String roleIds = empService.findEmpRoleIds(Integer.valueOf(emp.getEmpId()));
        if (roleIds.indexOf("18") != -1)  roleids = orgId + ".18";

        /* 根据empId查询roleIds */
        String taskId = eactServer.findTaskIdByObjecIdAndAssigneeIsNull(Event.class.getSimpleName(), eventId, roleids);

        /* draw_time */
        drawTimeService.save(emp.getEmpId().toString(), eventId, orgId);

        /* 更新update_time */
        Event event = eventService.findOneByEventId(eventId);
        event.setUpdateTime(new Date());
        event.setEventStatus(0);
        eventService.updateEvent(event);

        return eactServer.claim(taskId, String.valueOf(emp.getEmpId()));
    }

    /**
     * 完成任务
     *
     * @param taskId
     * @param outCome
     * @param comment
     * @param userMassage
     * @param assignee
     * @param assigneeList
     * @return String
     */
    @RequestMapping("/completeTask")
    public String completeTask(HttpServletRequest request, Event event1, String taskId, String outCome, String comment, String userMassage, String assignee, String assigneeList) throws ParseException {
        /* 当前事件 */
        String key = easyActService.findBuniness_keyByTaskId(taskId);
        String id = key.substring(6, key.length());
        Event event = eventService.findOneByEventId(id);

        if ("交办执办".equals(outCome) || "派遣执办".equals(outCome)) assignee = assigneeList;
        assignee = assignee.substring(0, assignee.length() - 1);

        /* 当前登陆人姓名及信息 */
        Map<String, Cookie> cookieMap = HelperClazz.ReadCookieMap(request);
        Cookie cookie = (Cookie) cookieMap.get("userName");
        String userName = cookie.getValue().replace("'", "");
        SysEmp emp = empService.getEmpByLogin(userName);


        /* 更新event_type_id */
        event.setEventTypeId(kvService.getKVByVal(outCome).get(0).getKvId());
        event.setUpdateTime(new Date());
        event.setEventStatus(0);
        eventService.updateEvent(event);

        String messageAccessoryIds = eventService.saveMessageAccessory(event1.getImgStr(), event1.getAudioStr(), event1.getVedioStr(), event.getEventId().toString());
        userMassage = this.getUserMassage(emp.getEmpId(), messageAccessoryIds, outCome);
        String orgId = empOrgService.getOrgByempId(emp.getEmpId()).get(0).getOrgId();

        /* draw_time */
        if("派遣执办".equals(outCome) || "交办执办".equals(outCome)){
            String[] str = assignee.split(",");
            for(int i=0;i<str.length;i++){
                drawTimeService.save(str[i], event.getEventId().toString(), orgId);
            }
        }

        assignee = eventService.getAssigne(outCome, assignee, orgId);
        assigneeList = assignee;

        if ("社区关单".equals(outCome) || "街道关单".equals(outCome)) {
            event.setUpdateTime(new Date());
            event.setEventStatus(1);
            eventService.updateEvent(event);
        }

        /* draw_time */
        DrawTime drawTime = drawTimeService.findDrawTimeByEmpIdAndEventId(event.getEventId().toString(), emp.getEmpId().toString());
        drawTime.setEventLink(kvService.getKVByVal(outCome).get(0).getKvId().toString());
        drawTimeService.update(drawTime);

        return eactServer.completeTask(taskId, outCome, comment, userMassage, assignee, assigneeList);
    }

    /**
     * 查看坐标
     *
     * @param id
     */
    @RequestMapping("/findCoordingByTaskId")
    public Map<String, Object> findCoordingByTaskId(String id) {
        String taskId = easyActService.findTaskIdByObjecId("Event", id);
        return easyActService.findCoordingByTask(taskId);
    }

    /**
     * 查看流程图
     *
     * @param id
     */
    @RequestMapping("viewImage")
    public void viewImage(String id) throws Exception {
        String taskId = easyActService.findTaskIdByObjecId("Event", id);
        String imgStr = eactServer.viewImage(taskId);
        byte[] imgByte = FileUtil.hex2byte(imgStr);
        InputStream in = new ByteArrayInputStream(imgByte);
//        InputStream in = new ByteArrayInputStream(str.getBytes("UTF-8"));
        // 3：从response对象获取输出流
        try {
            OutputStream out = response.getOutputStream();
            // 4：将输入流中的数据读取出来，写到输出流中
            for (int b = -1; (b = in.read()) != -1; ) {
                out.write(b);
            }
            // 将图写到页面上，用输出流写
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 任务回退到组任务
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/rollBackGroup")
    public String rollBackGroup(String taskId) {
        easyActService.rollbackGroup(taskId);
        return "任务回退到组任务";
    }

    /**
     * 任务返回上一节点
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/rollBackAct")
    public String rollBackAct(String taskId) {
        return easyActService.rollBackAct(taskId);
    }

    /**
     * 发布流程
     *
     * @return
     */
    @RequestMapping("/newdeploy")
    public String newdeploy(MultipartFile file, @RequestParam("filename") String filename) {
        return eactServer.newdeploy(file, filename);
    }

    /**
     * 获取下一步连线
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/findEvent")
    public Map<String, Object> findEvent(String taskId) {
        return easyActService.findEvent(taskId);
    }

    /**
     * 获取userMassage  部门_连线名称_登陆人姓名_附件Ids
     *
     * @param empId
     * @param messageAccessoryIds
     * @return
     */
    public String getUserMassage(Integer empId, String messageAccessoryIds, String outcome) {
        List<SysOrg> listOrg = empService.findOrgByEmpId(empId.toString());
        String orgNames = "";
        for (SysOrg org : listOrg) {
            orgNames += org.getOrgName() + ",";
        }
        // 如果含有部门名称信息 删最后一位符号
        if (orgNames != "" && orgNames != null) {
            orgNames = orgNames.substring(0, orgNames.length() - 1);
        }
        SysEmp emp = empService.findOne(empId);
        return orgNames + "_" + outcome + "_" + emp.getEmpName() + "_" + messageAccessoryIds;

    }

    /**
     * 查询历史意见
     *
     * @param eventId
     * @return
     */
    @RequestMapping("/findCommentByObjecId")
    public List<Comment> findCommentByObjecId(String eventId) {
        //根据taskId  查询历史记录
        List<Comment> list = eactServer.findCommentByObjecId("Event", eventId);
        return list;
    }

    /**
     * 上报事件 跳转index
     *
     * @author 姜文
     * @Param
     * @date 2018年3月6日, AM 09:35:51
     */
    @RequestMapping("/queryGridName")
    public Grid queryGridName(String smid) {
        Grid grid = gridService.findGridByCellId(smid).get(0);
        return grid;
    }

    /**
     * 事件详情
     *
     * @author 姜文
     * @Param
     * @date 2018年3月7日, PM 04:18:25
     */
    @RequestMapping("/eventInfo")
    public Event eventInfo(String eventId) {
        return eventService.findOneByEventId(eventId);
    }

    /**
     * 查询可上报的街道集合
     * 用于社区继续上报事件选择
     *
     * @return
     */
    @RequestMapping("/ChooseTheStreet")
    public List<SysOrg> ChooseTheStreet() {
        return sysOrgService.ChooseTheStreet();
    }

    /**
     * 根据当前登陆人ID获取当前登陆人所在街道（部门）可下派的社区
     *
     * @param empId
     * @return
     */
    public List<SysOrg> ChooseTheCommunity(Integer empId) {
        List<SysOrg> listOrg = empService.findOrgByEmpId(empId.toString());
        return sysOrgService.ChooseTheCommunity(listOrg.get(0).getOrgId());
    }

    /**
     * 查询已完成事件数量
     *
     * @return
     * @author yxd
     */
    @PostMapping("/queryEventChart")
    public List<Event> queryEventChart() {
        List<Event> finishList = eventService.queryFinishEventChart();
        List<Event> dealList = eventService.queryDealEventChart();
        List<Event> orgs = eventService.findAllDeparts();
            for (int i=0;i<orgs.size();i++) {
                for (Event event : finishList) {
                    if(orgs.get(i).getOrgName().equals(event.getOrgName())){
                        orgs.get(i).setFinishEventNum(event.getFinishEventNum());
                        orgs.get(i).setDealEventNum(event.getDealEventNum());
                    }
                }
                    for (Event event : dealList) {
                        if(orgs.get(i).getOrgName().equals(event.getOrgName())){
                            orgs.get(i).setDealEventNum(event.getDealEventNum());
                        }
                    }
            }


        return orgs;
    }

    /**
     * 查询网格长上报网格事件
     *
     * @return
     * @author yxd
     */
    @PostMapping("/queryWGEvent")
    public List<Event> queryWGEvent() {
        List<Event> finish = eventService.findWGEventFinish();//网格长完成事件数量
        List<Event> deal = eventService.findWGEventDeal();//网格长未完成事件数量
        List<Event> orgs = eventService.findAllDeparts();//所有社区

            for (int i=0;i<orgs.size();i++) {
                for (Event event : finish) {
                    if(orgs.get(i).getOrgName().equals(event.getOrgName())){
                        orgs.get(i).setFinishEventNum(event.getFinishEventNum());
                        orgs.get(i).setDealEventNum(event.getDealEventNum());
                    }
                }
                for (Event event : deal) {
                    if(orgs.get(i).getOrgName().equals(event.getOrgName())){
                        orgs.get(i).setDealEventNum(event.getDealEventNum());
                    }
                }
            }

        return orgs;
    }

    /**
     * 查询网格长上报治安事件
     *
     * @return
     * @author yxd
     */
    @PostMapping("/findSaveEvent")
    public List<Event> findSaveEvent() {
        List<Event> finish = eventService.findSaveEvent();//网格长完成事件数量
        List<Event> orgs = eventService.findAllDeparts();//所有社区
        if (orgs.size() > 0) {
            for (int j = 0; j < orgs.size(); j++) {
                if (finish.size() > 0) {
                    for (int i = 0; i < finish.size(); i++) {
                        if (orgs.get(j).getOrgName().equals(finish.get(i).getOrgName())) {
                            orgs.remove(j);
                        }
                    }
                }

            }
            finish.addAll(orgs);
        }
        return finish;
    }

}
